namespace SimpleWebServices.Web.UI.Html.Elements
{
    using System;
    using System.Xml;
    using System.Xml.Serialization;

    [XmlRoot("label")]
    public class Label : InnerElements, IAttributeAccesskey, IXmlSerializable
    {
        public Label()
        {
        }

        public Label(IControl control, string title)
            : this(control, title, title)
        {
        }

        public Label(IControl control, string title, string text)
        {
            this.Id = null == control ? null as Name : (Name)("label-" + (string)control.Id);
            this.For = null == control ? null as Name : control.Id;
            this.Title = title;
            this.Elements.Add(new TextString(text));
        }

        public char? Accesskey
        {
            get;
            set;
        }

        public Name For
        {
            get;
            set;
        }

        public override IElement Deserialize(string name, string type, string xml)
        {
            IElement result = null;

            if (null == type && "label".Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                result = xml.Deserialize<Label>();
            }

            return result;
        }

        public override void ReadXml(XmlReader reader)
        {
            string value = reader.GetAttribute("accesskey");
            if (!string.IsNullOrEmpty(value))
            {
                this.Accesskey = value[0];
            }

            value = reader.GetAttribute("for");
            if (!string.IsNullOrEmpty(value))
            {
                this.For = value;
            }

            base.ReadXml(reader);
        }

        public override void WriteXml(XmlWriter writer)
        {
            if (this.Accesskey.HasValue)
            {
                writer.WriteAttributeString("accesskey", this.Accesskey.Value.ToString());
            }

            if (null != this.For)
            {
                writer.WriteAttributeString("for", this.For);
            }

            base.WriteXml(writer);
        }
    }
}